package com.mike.uaa.server.authentication.converter;

import cn.hutool.core.util.StrUtil;
import com.mike.uaa.core.Authentication;
import com.mike.uaa.server.authentication.AuthorizationGrantType;
import com.mike.uaa.server.authentication.token.UsernamePasswordAuthenticationToken;
import com.mike.uaa.server.domain.request.AuthenticationRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author z
 */
public class UsernamePasswordAuthenticationConverter implements AuthenticationConverter {

    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String GRANT_TYPE = "grant_type";

    @Override
    public Authentication convert(AuthenticationRequest request) {

        if (!AuthorizationGrantType.PASSWORD.matches(request.getGrantType())) {
            return null;
        }
        // 获取用户输入的用户名和密码
        String username = Optional.ofNullable(request.getUsername()).orElse(StrUtil.EMPTY);
        String password = Optional.ofNullable(request.getPassword()).orElse(StrUtil.EMPTY);

        return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
    }

    @Override
    public Authentication convert(HttpServletRequest request) {
        if (!AuthorizationGrantType.PASSWORD.matches(request.getParameter(GRANT_TYPE))) {
            return null;
        }


        // 获取用户输入的用户名和密码
        String username = Optional.ofNullable(request.getParameter(USERNAME)).orElse(StrUtil.EMPTY);
        String password = Optional.ofNullable(request.getParameter(PASSWORD)).orElse(StrUtil.EMPTY);

        return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
    }
}
